<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="form" :model="listQuery" label-width="80px">
        <el-row :gutter="10">
          <el-col :lg="6" :xs="8" :sm="12">
            <el-form-item prop="iType" label="素材类型">
              <el-select v-model="listQuery.iType" placeholder="请选择素材类型">
                <el-option
                  v-for="item in optionType"
                  :key="item.id"
                  :label="item.strValue"
                  :value="item.strCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8" :sm="12">
            <el-form-item prop="strMaterialdetail" label="素材标签">
              <el-select v-model="listQuery.strMaterialdetail" placeholder="请选择素材标签">
                <el-option
                  v-for="item in optionTag"
                  :key="item.id"
                  :label="item.strValue"
                  :value="item.strCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8" :sm="12">
            <el-form-item prop="iOrgsysnum" label="机构名称">
              <el-cascader
                v-model="listQuery.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ expandTrigger: 'click', value:'strOrgnum',label:'strOrgname',children: 'yhlist', checkStrictly: true }"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :xs="8" :sm="12">
            <el-form-item prop="strOperator" label="操作者">
              <el-input v-model="listQuery.strOperator" placeholder="请输入操作者" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="10" :sm="12">
            <div style="margin: 0 0 20px 0">
              <el-button type="primary" @click="fetchList">搜索</el-button>
              <el-button @click="$refs['form'].resetFields()">重置</el-button>
              <el-button type="primary" @click="handleAddRow">添加</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="listData" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="iTypename" label="素材类型" align="center" />
        <el-table-column prop="strResolution" label="分辨率" align="center">
          <template slot-scope="{row}">{{ row.iType === 1 ? row.strResolution:'/' }}</template>
        </el-table-column>
        <el-table-column prop="strMaterialname" label="素材标签" align="center" />
        <!-- <el-table-column prop="strMaterialencode" label="素材编号" align="center" /> -->
        <el-table-column prop="strOrgname" label="机构名称" align="center" />
        <el-table-column prop="iDevtypename" label="设备类型" align="center" />
        <el-table-column prop="strDownload" label="素材下载链接" width="140" align="center">
          <template slot-scope="{row}">
            <a
              :href="row.strDownload"
              target="_barnd"
              style="color: #1890ff;text-decoration: underline;"
            >预览</a>
          </template>
        </el-table-column>
        <el-table-column prop="strOperatorname" label="操作者" align="center" />
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="{row}">
            <template v-if="row.iOrgsysnum === iOrgsysnum || iOrgsysnum === -1">
              <el-button size="mini" type="primary" @click="handleModify(row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
            <template v-else>/</template>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.pagenum"
        :limit.sync="limit"
        :layout="layout"
        @pagination="fetchList"
      />
      <!-- dialog -->

      <el-dialog
        :title="mTitle"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        @close="handleCancel"
      >
        <el-form ref="rulesForm" :model="addForm" :rules="rules" label-width="80px">
          <el-form-item prop="strMaterialname" label="素材名称">
            <el-input v-model="addForm.strMaterialname" placeholder="请输入素材名称" class="inptw200" />
          </el-form-item>
          <el-form-item prop="iType" label="素材类型">
            <el-select v-model="addForm.iType" placeholder="请选择素材类型" @change="handleChange">
              <el-option
                v-for="item in optionType"
                :key="item.id"
                :label="item.strValue"
                :value="item.strCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="strMaterialdetail" label="素材标签">
            <el-select v-model="addForm.strMaterialdetail" placeholder="请选择素材标签">
              <el-option
                v-for="item in optionTag"
                :key="item.id"
                :label="item.strValue"
                :value="item.strCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="iDevtype" label="设备类型">
            <el-select v-model="addForm.iDevtype" placeholder="请选择设备类型">
              <el-option
                v-for="item in iDevTypes"
                :key="item.id"
                :label="item.strValue"
                :value="item.strCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="strOperatorname" label="操作者">
            <el-col :span="12">
              <el-input v-model="addForm.strOperator" disabled class="inptw200" />
            </el-col>
          </el-form-item>
          <el-form-item prop="iOrgsysnum" label="机构名称">
            <el-col :span="12">
              <el-cascader
                v-model="addForm.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                disabled
                placeholder="总行"
                :props="{ expandTrigger: 'hover',checkStrictly: true, value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-col>
          </el-form-item>

          <el-form-item v-if="addForm.iType === '1'" prop="strDownload" label="图片上传">
            <el-upload
              class="avatar-uploader"
              :action="baseImgRUL"
              name="uploadFile"
              :show-file-list="false"
              :on-success="(response, file)=>handleSuccess(response, file, 'addForm', 'strDownload','strMaterialsize')"
              :before-upload="beforeUpload"
            >
              <img v-if="addForm.strDownload" :src="addForm.strDownload" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

          <el-form-item v-else-if="addForm.iType === '2'" prop="strDownload" label="视频地址">
            <el-upload
              class="avatar-uploader"
              :action="baseImgRUL"
              name="uploadFile"
              :show-file-list="false"
              :on-success="(response, file)=>handleVideoSuccess(response, file, 'addForm', 'strDownload','strMaterialsize')"
              :before-upload="beforeUploadVideo"
              :on-progress="uploadVideoProcess"
            >
              <video
                v-if="addForm.strDownload !=''&& videoFlag == false"
                :src="addForm.strDownload"
                class="avatar"
                controls="controls"
              >您的浏览器不支持视频播放</video>
              <i
                v-else-if="addForm.strDownload =='' && videoFlag == false"
                class="el-icon-plus avatar-uploader-icon"
              />
              <el-progress
                v-if="videoFlag == true"
                type="circle"
                :percentage="videoUploadPercent"
                style="margin-top:30px;"
              />
            </el-upload>
          </el-form-item>
          <el-form-item v-else prop="strDownload" label="文件地址">
            <el-input v-model="addForm.strDownload" placeholder="请输入文件地址" />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button v-if="mTitle === dialogTitle.add" type="primary" @click="dialogAddMatrt">确 定</el-button>
          <el-button v-else type="primary" @click="dialogEditMatrt">修 改</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getMaterList,
  getOrglist,
  getSysType,
  addMaterial,
  deleteMaterial
} from '../../api/addTag'
import { updateMaterInfo } from '@/api/material/index'
import mixins from '@/mixins/uploadImg'
import Pagination from '@/components/Pagination/index'
import { validURL } from '../../utils/validate'
import { validateValue } from '../../utils/validateForm'
import { getParentNumArr } from '../../api/common'
import { mapGetters } from 'vuex'

export default {
  name: 'Material',
  components: { Pagination },
  mixins: [mixins],
  props: {},
  data() {
    var validateURL = (rule, value, callback) => {
      if (this.addForm.iType === '1') {
        if (value === '') {
          callback(new Error('请上传图片'))
        } else {
          callback()
        }
      } else if (this.addForm.iType === '2') {
        if (value === '') {
          callback(new Error('请上传视频'))
        } else {
          callback()
        }
      } else {
        if (value === '') {
          callback(new Error('文件地址不能为空！'))
        } else if (!validURL(value)) {
          callback(new Error('请输入正确的地址!'))
        } else {
          callback()
        }
      }
    }
    return {
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper',
      model: '',
      mTitle: '',
      dialogTitle: {
        add: '添加素材',
        edit: '修改素材'
      },
      dialogVisible: false,
      imageUrl: '',
      strOrgnum: [],
      mixUploadUrl: '',
      listQuery: {
        iType: '',
        strMaterialdetail: '',
        iOrgsysnum: '',
        iOrgnum: 1,
        strOperator: '',
        pagenum: 1
      },
      addForm: {
        strMaterialname: '',
        iType: '',
        strMaterialdetail: '',
        iOrgsysnum: [],
        strOperator: 'admin',
        strResolution: '', // 分辨率
        iDevtype: '', // 设备类型
        strDownload: '', // 视频下载地
        strMaterialsize: '' // 上传图片或者视频大小
      },
      listData: [],
      options: [],
      optionType: [],
      optionTag: [],
      iDevTypes: [],
      rules: {
        strMaterialname: [
          {
            required: true,
            validator: validateValue,
            message: '请输入素材名称',
            trigger: 'blur'
          }
        ],
        iType: [
          { required: true, message: '请选择素材类型', trigger: 'change' }
        ],
        strMaterialdetail: [
          { required: true, message: '请选择素材标签', trigger: 'change' }
        ],
        iDevtype: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        // strDownload: [
        //   { required: true, message: '图片上传', trigger: 'blur' }
        // ],
        strDownload: [
          { required: true, validator: validateURL, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum', 'name', 'userID'])
  },
  watch: {
    'addForm.strDownload': {
      handler(newVal, oldVal) {
        if (this.addForm.iType === '1') {
          const img = new Image()
          img.src = newVal
          img.onload = () => {
            if (img.complete) {
              this.addForm.strResolution = img.width + '*' + img.height
            }
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.fetchList()
    this.getSelectList()
    this.addForm.strOperator = this.name || 'Super Admin'
    this.modifySysNum()
    this.mTitle = this.dialogTitle.add
    console.log(typeof this.iOrgsysnum)
  },
  methods: {
    modifySysNum() {
      getParentNumArr({ iOrgsysnum: this.iOrgsysnum }).then(res => {
        if (this.iOrgsysnum === -1) {
          this.addForm.iOrgsysnum = ['-1']
          return this.addForm.iOrgsysnum
        }
        if (res.data && res.data.indexOf(',') > 0) {
          this.addForm.iOrgsysnum = res.data.split(',')
        } else {
          this.addForm.iOrgsysnum = [res.data]
        }
      })
    },
    getSelectList() {
      getOrglist().then(res => {
        this.options = res.data
      })
      /**
         * @param(3) 素材标签
         * @param(4) 素材类型
         * @param(7) 设备类型
         */
      getSysType({ typeInfo: [3, 4, 7] }).then(res => {
        this.optionType = res.data[4]
        this.optionTag = res.data[3]
        this.iDevTypes = res.data[7]
      })
    },
    fetchList() {
      if (this.listQuery.iOrgsysnum instanceof Array) {
        this.listQuery.iOrgsysnum = this.listQuery.iOrgsysnum.splice(-1)[0]
      }
      this.listQuery.iOrgnum = this.iOrgsysnum
      getMaterList(this.listQuery).then(res => {
        this.listData = res && res.data
        this.total = !res ? 0 : res.total
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        deleteMaterial({ idInfo: [row.id] })
          .then(res => {
            this.$notify({
              title: '操作成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.fetchList()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    handleModify(row) {
      // this.addForm = new Set([...this.addForm, ...row])
      const addForm = {
        strMaterialname: row.strMaterialname,
        iType: row.iType.toString(),
        strMaterialdetail: row.strMaterialdetail,
        iOrgsysnum: row.iOrgsysnum,
        strOperator: row.strOperator,
        strResolution: row.strResolution, // 分辨率
        iDevtype: row.iDevtype.toString(), // 设备类型
        strDownload: row.strDownload, // 视频下载地
        strMaterialsize: row.strMaterialsize, // 上传图片或者视频大小
        id: row.id
      }
      getParentNumArr({ iOrgsysnum: addForm.iOrgsysnum }).then(res => {
        if (res.data.indexOf(',') > 0) {
          addForm.iOrgsysnum = res.data.split(',')
        } else {
          addForm.iOrgsysnum = [res.data]
        }
      })
      // this.addForm = row
      // this.addForm.iType = row.iType.toString()
      // this.addForm.iDevtype = row.iDevtype.toString()
      this.addForm = addForm
      this.mTitle = this.dialogTitle.edit
      this.dialogVisible = true
    },
    handleAddRow() {
      this.mTitle = this.dialogTitle.add
      this.dialogVisible = true
    },
    handleCancel() {
      this.dialogVisible = false
      this.$refs['rulesForm'].resetFields()
      this.mTitle = this.dialogTitle.add
      this.addForm = {
        strMaterialname: '',
        iType: '',
        strMaterialdetail: '',
        iOrgsysnum: [],
        strOperator: this.name,
        strResolution: '', // 分辨率
        iDevtype: '', // 设备类型
        strDownload: '' // 视频下载地
      }
      this.modifySysNum()
    },
    handleChange(val) {
      if (val === '1') {
        this.$refs['rulesForm'].clearValidate('strDownload')
        this.addForm.strDownload = ''
      } else {
        this.addForm.strDownload = ''
      }
    },
    dialogAddMatrt() {
      if (this.addForm.iOrgsysnum instanceof Array) {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1)[0]
      }
      this.$refs['rulesForm'].validate(valid => {
        if (valid) {
          const query = this.addForm
          query.strOperator = this.userID
          addMaterial(query).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.fetchList()
            this.dialogVisible = false
            this.$refs['rulesForm'].resetFields()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    dialogEditMatrt() {
      if (this.addForm.iOrgsysnum instanceof Array) {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1)[0]
      }
      this.$refs['rulesForm'].validate(valid => {
        if (valid) {
          const query = this.addForm
          query.strOperator = this.userID
          updateMaterInfo(query).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.fetchList()
            this.$refs['rulesForm'].resetFields()
            this.dialogVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
